package me.zhengjie.tool;


import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.math.BigDecimal;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;


/**
 * @ClassName PDFUtil
 * @Description: PDF转换工具
 * @Company: com.yinhai
 * @author huangyh
 * @date 2016年8月1日
 * @version 1.0
 */
public class PDFUtil {
	private static int BLACK = 0x000000;
	private static int WHITE = 0xFFFFFF;
	private static Map specialConfigMap = new HashMap();
	static {
		String special_6501_001 = "/resource/lodop/special_6501/special_6501_001.png";//养老处专用章

		BigDecimal sealWidth = BigDecimal.valueOf(100f);
		BigDecimal sealHeight = BigDecimal.valueOf(100f);
		Map special_302 = new HashMap();//养老处专用章
		Map special_200 = new HashMap();//养老处专用章
		special_302.put("imgPath",special_6501_001);
		special_302.put("sealWidth",sealWidth);
		special_302.put("sealHeight",sealHeight);
		special_200.putAll(special_302);

		//打印位置，直接用绝对位置
		special_302.put("absoluteX",BigDecimal.valueOf(350f));//盖住审//370f 盖住人
		special_302.put("absoluteY",BigDecimal.valueOf(200f));//盖住审//200f 盖住人
		//打印位置，直接用绝对位置
		special_200.put("absoluteX",BigDecimal.valueOf(404f));
		special_200.put("absoluteY",BigDecimal.valueOf(252f));

		specialConfigMap.put("302",special_302);
		specialConfigMap.put("200",special_200);

		specialConfigMap.put("I10040",special_302);

		// 克拉玛依油田
		String special_659904_001 = "/resource/lodop/special_659904/special_659904_001.png";// 克拉玛依油田
		Map special_659904 = new HashMap();//养老处专用章
		special_659904.put("imgPath",special_659904_001);
		special_659904.put("sealWidth",sealWidth);
		special_659904.put("sealHeight",sealHeight);
		special_659904.put("absoluteX",BigDecimal.valueOf(350f));//盖住审//370f 盖住人
		special_659904.put("absoluteY",BigDecimal.valueOf(200f));//盖住审//200f 盖住人
		specialConfigMap.put("twp13",special_659904); // 基本养老 + 机关养老
		specialConfigMap.put("twp14",special_659904); // 基本医疗
		specialConfigMap.put("twp15",special_659904); // 原机关养老
		specialConfigMap.put("twp16",special_659904); // 工伤
		specialConfigMap.put("twp17",special_659904); // 医疗大额
		specialConfigMap.put("twp18",special_659904); // 生育
		specialConfigMap.put("twp19",special_659904); // 失业
		specialConfigMap.put("twp20",special_659904); // 职业年金


		//锁死map，不允许进行变更
		specialConfigMap = Collections.unmodifiableMap(specialConfigMap);
	}
	/*public static void pdfToImage(String pdfUrl, String imgTempUrl, String imgType) {
		File pdf = new File(pdfUrl);
		String fileName = pdf.getName();
		fileName = fileName.substring(0, fileName.lastIndexOf("."));
		imgTempUrl = !imgTempUrl.endsWith("/") && !imgTempUrl.endsWith("\\") ? imgTempUrl + "/" : imgTempUrl;
		try {
			FileUtil.createFolder(imgTempUrl);
			// 读入PDF
			InputStream input = new FileInputStream(pdfUrl);
			ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
			readInputStream(input, outputstream);
			input.close();
			PdfReader pdfReader = new PdfReader(outputstream.toByteArray());
			//PdfReader pdfReader = new PdfReader(pdfUrl);
			// 计算PDF页码数
			int pageCount = pdfReader.getNumberOfPages();
			// 循环每个页码
			for (int i = pageCount; i >= pdfReader.getNumberOfPages(); i--) {
				pdfReader = new PdfReader(outputstream.toByteArray());
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				PdfStamper pdfStamper = null;
				PDDocument pdDocument = null;
				pdfReader.selectPages(String.valueOf(i));
				pdfStamper = new PdfStamper(pdfReader, out);
				pdfStamper.close();
				// 利用PdfBox生成图像
				pdDocument = PDDocument.load(new ByteArrayInputStream(out.toByteArray()));
				PDPage page = (PDPage) pdDocument.getDocumentCatalog().getAllPages().get(0);
				String saveFileName = imgTempUrl + fileName + "_" + i + "." + imgType;
				// pdfPage2Img(page, saveFileName, imgType);
				OutputStream outputStream = new FileOutputStream(saveFileName);
				ImageOutputStream output = ImageIO.createImageOutputStream(outputStream);
				BufferedImage image = page.convertToImage();
				ImageIOUtil.writeImage(image, imgType, outputStream, 96);
				if (output != null) {
					output.flush();
					output.close();
				}
				image.flush();
				pdDocument.close();
				out.close();
				outputStream.close();
				pdfReader.close();
			}
		} catch (Exception e) {
			LogUtil.error(e);
		}
	}*/

	//by huangyh
	/*public static List<InputStream>  pdfToImageByStream(OutputStream outputStream, String imgType){
		return icepdfToImageByStream(outputStream, imgType);
	}*/

	//将传入的pdf流转换成图片流（可能生成多张图片）     20171013hucf
	/*private static List<InputStream> pdfboxToImageByStream(OutputStream outputStream, String imgType) {
		List<InputStream> inputStreams = new ArrayList<InputStream>();
		try {
			PdfReader pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
			int pageCount = pdfReader.getNumberOfPages();
			for (int i = pageCount; i >= pdfReader.getNumberOfPages(); i--) {
				pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				PdfStamper pdfStamper = null;
				PDDocument pdDocument = null;
				pdfReader.selectPages(String.valueOf(i));
				pdfStamper = new PdfStamper(pdfReader, out);
				pdfStamper.close();
				// 利用PdfBox生成图像
				pdDocument = PDDocument.load(new ByteArrayInputStream(out.toByteArray()));
				PDPage page = (PDPage) pdDocument.getDocumentCatalog().getAllPages().get(0);
				BufferedImage image = page.convertToImage();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(image, imgType, baos);
				ByteArrayInputStream baoi = new ByteArrayInputStream(baos.toByteArray());
				inputStreams.add(baoi);
				image.flush();
				baos.close();
				baoi.close();
				out.close();
				pdDocument.close();
				pdfReader.close();
			}
		} catch (IOException e) {
			LogUtil.error(e);
		} catch (com.itextpdf.text.DocumentException e) {
			// TODO Auto-generated catch block
			LogUtil.error(e);
		}
		return inputStreams;
	}*/

	/**
	 * @Title: pdfToImageByStream
	 * @Description: byhuangyh 20180109
	 * @param outputStream
	 * @param imgType
	 * @return 
	 * List<InputStream>  
	 */
	/*private static List<InputStream> icepdfToImageByStream(OutputStream outputStream, String imgType) {
		if (ObjectUtil.isEmpty(outputStream)) {
			return null;
		}
		List<InputStream> inputStreams = new ArrayList<InputStream>();
		org.icepdf.core.pobjects.Document document = new org.icepdf.core.pobjects.Document();
		byte[] pdfByte =((ByteArrayOutputStream)outputStream).toByteArray();
		try{
		document.setByteArray(pdfByte, 0, pdfByte.length, null);
		}catch (Exception e){

		}
		float scale = 3.0f;//缩放比例
		float rotation = 0f;//旋转角度
		ByteArrayOutputStream baos = null;
		ByteArrayInputStream baoi=null;
		try {
			for (int i = 0; i < document.getNumberOfPages(); i++) {
				BufferedImage image = (BufferedImage)
						document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);
				RenderedImage rendImage = image;
				// String imgName = Math.random() + "."+imgType;
				//File file = new File("/home/weblogic/Desktop/" + imgName);
				//ImageIO.write(rendImage,imgType, file);
				baos = new ByteArrayOutputStream();
				ImageIO.write(rendImage, imgType, baos);
				baoi = new ByteArrayInputStream(baos.toByteArray());
				inputStreams.add(baoi);
				image.flush();
				baos.close();
				baoi.close();
			}
		} catch (IOException e) {
			LogUtil.error(e);
		}catch (Exception e){
			LogUtil.error(e);
		}
		finally{
			try{
				if(baos!=null){
					baos.close();
				}
				if(baoi!=null){
					baoi.close();
				}
			}
			catch(Exception ex){
			}
			document.dispose();
		}
		return inputStreams;
	}*/

	// private static void pdfPage2Img(PDPage page, String saveFileName, String
	// imgType) throws IOException {
	// BufferedImage img_temp = page.convertToImage();
	// Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix(imgType);
	// ImageWriter writer = (ImageWriter) it.next();
	// ImageOutputStream imageout = ImageIO.createImageOutputStream(new
	// FileOutputStream(saveFileName));
	// writer.setOutput(imageout);
	// writer.write(new IIOImage(img_temp, null, null));
	// if (imageout != null) {
	// imageout.flush();
	// imageout.close();
	// }
	// }

	/**
	 * 图片转换为PDF
	 *
	 * @param destPath
	 *            生成pdf文件的路径
	 * @param imagesPath
	 *            需要转换的图片路径的数组
	 * @throws IOException
	 * @throws DocumentException
	 */
	/*public static void imagesToPdf(String destPath, String imagesPath) {
		try {
			// 第一步：创建一个document对象。
			Document document = new Document();
			document.setMargins(0, 0, 0, 0);
			// 第二步：
			// 创建一个PdfWriter实例，
			PdfWriter.getInstance(document, new FileOutputStream(destPath));
			// 第三步：打开文档。
			document.open();
			// 第四步：在文档中增加图片。
			File files = new File(imagesPath);
			String[] images = files.list();
			int len = images.length;

			for (int i = 0; i < len; i++) {
				if (images[i].toLowerCase().endsWith(".bmp")) {
					String temp = imagesPath + "\\" + images[i];
					Image img = Image.getInstance(temp);
					img.setAlignment(Image.ALIGN_CENTER);
					// 根据图片大小设置页面，一定要先设置页面，再newPage（），否则无效
					document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
					document.newPage();
					document.add(img);
				}
			}
			// 第五步：关闭文档。
			document.close();
		} catch (Exception e) {
			LogUtil.error(e);
		}
	}*/

	/**
	 * 合并pdf文档
	 *
	 * @param files
	 *            待合并的文件路径
	 * @param targetPath
	 *            合并后的文件路径
	 */
	/*public static void mergePdfFiles(String[] files, String targetPath) throws Exception {
		com.lowagie2.text.Document document = new com.lowagie2.text.Document(new com.lowagie2.text.pdf.PdfReader(files[0]).getPageSize(1));
		com.lowagie2.text.pdf.PdfCopy copy = new com.lowagie2.text.pdf.PdfCopy(document, new FileOutputStream(targetPath));
		document.open();
		for (int i = 0; i < files.length; i++) {
			com.lowagie2.text.pdf.PdfReader reader = new com.lowagie2.text.pdf.PdfReader(files[i]);
			int n = reader.getNumberOfPages();
			for (int j = 1; j <= n; j++) {
				document.newPage();
				com.lowagie2.text.pdf.PdfImportedPage page = copy.getImportedPage(reader, j);
				copy.addPage(page);
			}
		}
		document.close();
	}*/

	//合并pdf流至一个pdf    20171013byhucf
	/*public static void mergePdfFilesByStream(List<InputStream> files, OutputStream outputStream) throws Exception {
		if (ObjectUtil.isEmpty(files)) {
			return;
		}
		//一个inputstream只能被读一次，下一次就读不出东西了
		//以下部分有两次要用到一个流，所以先统一读出来放在byte中,否则第二次读会失败
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		readInputStream(files.get(0), output);
		com.lowagie2.text.Document document = new com.lowagie2.text.Document(new com.lowagie2.text.pdf.PdfReader(output.toByteArray()).getPageSize(1));
		com.lowagie2.text.pdf.PdfCopy copy = new com.lowagie2.text.pdf.PdfCopy(document, outputStream);
		document.open();
		for (int i = 0; i < files.size(); i++) {
			com.lowagie2.text.pdf.PdfReader reader = null;
			if (i == 0) {
				reader = new com.lowagie2.text.pdf.PdfReader(output.toByteArray());
			} else {
				reader = new com.lowagie2.text.pdf.PdfReader(files.get(i));
			}
			if (!ObjectUtil.isEmpty(reader)) {
				int pageNum = reader.getNumberOfPages();
				for (int j = 1; j <= pageNum; j++) {
					document.newPage();
					com.lowagie2.text.pdf.PdfImportedPage page = copy.getImportedPage(reader, j);
					copy.addPage(page);
				}
			}
		}
		document.close();
	}*/

	/**
	 * 给pdf文件生成条码、页眉图片
	 *
	 * @param reportParam
	 *            报表参数
	 * @param BarConfig
	 *            条码配置信息
	 * @throws IOException
	 * @throws DocumentException
	 */
	/*public static void pdfAddBarcodeAndHeader(OutputStream outputStream, Map<String, Object> reportParam, Map<String, Object> BarConfig) {
		try {
			if (ObjectUtil.isEmpty(BarConfig) || ObjectUtil.isEmpty(outputStream)) {
				return;
			}
			Map<String, String> barcodeCfg = (Map<String, String>) BarConfig.get("barcode_tag");
			if (!ObjectUtil.isEmpty(barcodeCfg)) {
				String bar_content_re = PlaceholderUtil.resolvePlaceholders((String) barcodeCfg.get("bar_content"), Object2String(reportParam), "null");
				barcodeCfg.put("bar_content", bar_content_re);
			}
			Map<String, String> qrcodeCfg = (Map<String, String>) BarConfig.get("qrcode_tag");
			if (!ObjectUtil.isEmpty(qrcodeCfg)) {
				String qr_content_re = PlaceholderUtil.resolvePlaceholders((String) qrcodeCfg.get("bar_content"), Object2String(reportParam), "null");
				qrcodeCfg.put("bar_content", qr_content_re);
			}
			Map<String, String> headerCfg = (Map<String, String>) BarConfig.get("header_tag");
			PdfReader pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
			Rectangle rect = pdfReader.getPageSize(1);
			Image img = null;
			PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
			PdfContentByte over = pdfStamper.getOverContent(1);
			// 一维码
			if (BaseConstant.YES.equals(BarConfig.get("is_barcode_tag"))) {
				BigDecimal width = new BigDecimal(barcodeCfg.get("bar_width"));
				BigDecimal height = new BigDecimal(barcodeCfg.get("bar_height"));
				BigDecimal x = new BigDecimal(barcodeCfg.get("bar_left"));
				BigDecimal y = BigDecimal.valueOf(rect.getHeight()).subtract(new BigDecimal(barcodeCfg.get("bar_top"))).subtract(height);
				Barcode128 code128 = new Barcode128();
				code128.setCode(barcodeCfg.get("bar_content"));
				img = code128.createImageWithBarcode(over, BaseColor.BLACK,BaseColor.BLACK);
				img.scaleAbsolute(width.floatValue(), height.floatValue());// 控制图片大小
				if (x.compareTo(BigDecimal.valueOf(rect.getWidth()).subtract( width))>0 ) {
					x = BigDecimal.valueOf(rect.getWidth()) .subtract(width).subtract(BigDecimal.valueOf(10)) ;
				}
				img.setAbsolutePosition(x.floatValue(), y.floatValue());// 控制图片位置
				if (SibpmConstant.YES.equals(barcodeCfg.get("is_every"))) {
					//每一页都加上一维码
					for (int j=1; j<=pdfReader.getNumberOfPages(); j++) {
						over = pdfStamper.getOverContent(j);
						over.addImage(img);
					}
				} else {
					over.addImage(img);
				}

			}// 二维码
			if (BaseConstant.YES.equals(BarConfig.get("is_qrcode_tag"))) {
				BigDecimal width = new BigDecimal(qrcodeCfg.get("bar_width"));
				BigDecimal height = new BigDecimal(qrcodeCfg.get("bar_height"));
				BigDecimal x = new BigDecimal(qrcodeCfg.get("bar_left"));
				BigDecimal y = BigDecimal.valueOf(rect.getHeight()).subtract(new BigDecimal(qrcodeCfg.get("bar_top"))).subtract(height) ;
				if (x .compareTo(BigDecimal.valueOf(rect.getWidth()) .subtract(width) )>0 ) {
					x = BigDecimal.valueOf(rect.getWidth()) .subtract(width)  .subtract(BigDecimal.valueOf(10));
				}
				Map<EncodeHintType,Object> hint = new HashMap<EncodeHintType,Object>();
				hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
				hint.put(EncodeHintType.CHARACTER_SET, "utf-8");
				hint.put(EncodeHintType.MARGIN, 0);
				MultiFormatWriter writer = new MultiFormatWriter();
				BufferedImage qrcodeImage = null;
				//创建二维码矩阵
				BitMatrix bitMatrix = writer.encode(qrcodeCfg.get("bar_content"), BarcodeFormat.QR_CODE, width.intValue(), height.intValue(), hint);
				try {
					bitMatrix = deleteMatrixWhite(bitMatrix);
				} catch (Exception e) {
					LogUtil.error(e);
				}
				int matrixWidth = bitMatrix.getWidth();
				int matrixHeight = bitMatrix.getHeight();
				qrcodeImage = new BufferedImage(matrixWidth, matrixHeight+10, BufferedImage.TYPE_INT_RGB);
				Graphics2D  graphics = qrcodeImage.createGraphics();
				graphics.setColor(Color.WHITE);
				graphics.fillRect(0, 0, matrixWidth, matrixHeight+10);
				//将二维矩阵画成图片
				for(int j=0; j<matrixWidth; j++){
					for(int k=0; k<matrixHeight; k++){
						qrcodeImage.setRGB(j, k, bitMatrix.get(j, k) ? BLACK : WHITE);
					}
				}
				//给二维码中间加logo图片
				String imgPath = "/resource/lodop/logo.png";
				InputStream logoInputstream = PDFUtil.class.getClassLoader().getResourceAsStream(imgPath);
				BufferedImage logoImg = ImageIO.read(logoInputstream);
//				graphics.drawImage(logoImg, matrixWidth*7/24, matrixHeight*7/24, matrixWidth*5/12, matrixWidth*5/12, null);
				graphics.drawImage(logoImg, matrixWidth/3, matrixHeight/3, matrixWidth/3, matrixWidth/3, null);
				graphics.dispose();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageOutputStream imOut;
				imOut = ImageIO.createImageOutputStream(baos);
				ImageIO.write(qrcodeImage, "jpg", imOut);
				InputStream zxing_is = new ByteArrayInputStream(baos.toByteArray());
				img = getImgByInputstream(zxing_is);
//				BarcodeQRCode qrcode = new BarcodeQRCode(qrcodeCfg.get("bar_content"), 1, 1, null);
//				img = qrcode.getImage();
				img.setAlignment(Element.ALIGN_CENTER);
				img.scaleAbsolute(width.floatValue(), height.floatValue());// 控制图片大小
				img.setAbsolutePosition(x.floatValue(), y.floatValue());// 控制图片位置
				BaseFont font = null;
				try {
					font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				} catch (Exception e) {
					LogUtil.error(e);
				}
				for (int j=1; j<=pdfReader.getNumberOfPages(); j++) {
					over = pdfStamper.getOverContent(j);
					over.addImage(img);
					if (!ObjectUtil.isEmpty(font)) {
						over.beginText();
						over.setFontAndSize(font, 10);
						//新疆需求：二维码下方显示单据id
						if (!ObjectUtil.isEmpty(qrcodeCfg.get("bar_content"))) {
							if (qrcodeCfg.get("bar_content").length() > 15) {
								qrcodeCfg.put("bar_content", qrcodeCfg.get("bar_content").substring(0, 15));
							}
						}
						over.showTextAligned(Element.ALIGN_CENTER, qrcodeCfg.get("bar_content"), x.add(width.divide(BigDecimal.valueOf(2))).floatValue(), y.floatValue(), 0);
						over.endText();
					}
					//如果不是配置的每页都添加
					if (!SibpmConstant.YES.equals(qrcodeCfg.get("is_every"))) {
						break;
					}
				}
			}//页眉
			if (BaseConstant.YES.equals(BarConfig.get("is_header_tag")) && !ObjectUtil.isEmpty(headerCfg)) {
				BigDecimal width = new BigDecimal(headerCfg.get("bar_width"));
				BigDecimal height = new BigDecimal(headerCfg.get("bar_height"));
				BigDecimal x = new BigDecimal(headerCfg.get("bar_left"));
				BigDecimal y = BigDecimal.valueOf(rect.getHeight()) .subtract( new BigDecimal(headerCfg.get("bar_top"))) .subtract(height);
				if (x .compareTo(BigDecimal.valueOf(rect.getWidth()) .subtract(width) )>0 ) {
					x = BigDecimal.valueOf(rect.getWidth()).subtract(width)  .subtract(BigDecimal.valueOf(10)) ;
				}
				String imgPath = "/resource/lodop/sibpm_page_header.png";
				InputStream pageHeaderInputstream = PDFUtil.class.getClassLoader().getResourceAsStream(imgPath);
				Image pageHeaderImg = getImgByInputstream(pageHeaderInputstream);
				pageHeaderImg.setAlignment(Element.ALIGN_CENTER);
				pageHeaderImg.scaleAbsolute(width.floatValue(), height.floatValue());// 控制图片大小
				pageHeaderImg.setAbsolutePosition(x.floatValue(), y.floatValue());// 控制图片位置
				//每一页都加上
				for (int j=1; j<=pdfReader.getNumberOfPages(); j++) {
					over = pdfStamper.getOverContent(j);
					over.addImage(pageHeaderImg);
					if (!SibpmConstant.YES.equals(headerCfg.get("is_every"))) {
						break;
					}
				}
			}
			pdfStamper.close();
		} catch (Exception e) {
			LogUtil.error(e);
			throw new IllegalArgumentException("报表标签配置有误，请检查");
		}
	}*/

	/**
	 * 去掉白边
	 * @param matrix
	 * @return
	 */
	/*private static BitMatrix deleteMatrixWhite(BitMatrix matrix) {
		int[] rec = matrix.getEnclosingRectangle();
		int resWidth = rec[2] + 1;
		int resHeight = rec[3] + 1;

		BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
		resMatrix.clear();
		for (int i = 0; i < resWidth; i++) {
			for (int j = 0; j < resHeight; j++) {
				if (matrix.get(i + rec[0], j + rec[1]))
					resMatrix.set(i, j);
			}
		}
		return resMatrix;
	}*/

	/**
	 * 给pdf文件生成签字
	 *
	 * @param outputStream pdf流
	 * @param is 签字图片流
	 * @param signConfig 签字配置信息
	 * @throws IOException
	 * @throws DocumentException
	 */
	/*public static void pdfAddSign(OutputStream outputStream, InputStream is, Map<String,Object> signConfig) {
		if (ObjectUtil.isEmpty(signConfig) || ObjectUtil.isEmpty(outputStream) || ObjectUtil.isEmpty(is)) {
			return;
		}
		if (!SibpmConstant.YES.equals(signConfig.get("is_sign_tag"))) {
			return;
		}
		try {
			InputStream date_is = null;
			PdfReader pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
			int pageNum = pdfReader.getNumberOfPages();
			Map<String, String> signCfg = (Map<String, String>) signConfig.get("sign_tag");
			final List<float[]> arrays = new ArrayList<float[]>();
			final List<float[]> date_arrays = new ArrayList<float[]>();
			if (!ObjectUtil.isEmpty(signCfg)) {
				BigDecimal width = BigDecimal.valueOf(50);
				BigDecimal height = BigDecimal.valueOf(30);
				if (!ObjectUtil.isEmpty(signCfg.get("bar_width"))) {
					width = new BigDecimal(signCfg.get("bar_width"));
				}
				if (!ObjectUtil.isEmpty(signCfg.get("bar_height"))) {
					height = new BigDecimal(signCfg.get("bar_height"));
				}
				//如果有关键字，则先搜索关键字的坐标
				final String KEY_WORD = signCfg.get("bar_content");
				final String DATE_KEY_WORD = "签收时间";
				List<String> key_words = ListUtil.parseList(KEY_WORD, ",");
				if (!ObjectUtil.isEmpty(KEY_WORD)) {
					for (final String key_word : key_words) {
						//配置了多个关键字的，挨个找，找到了就跑
						if (!ObjectUtil.isEmpty(arrays)) {
							break;
						}
						if (!ObjectUtil.isEmpty(key_word)) {
							PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
							for (int i = 1; i <= pageNum; i++) {
								final int finalI = i;
								pdfReaderContentParser.processContent(i, new RenderListener() {
									private StringBuilder pdfsb = new StringBuilder();
									private float yy = -1f;
									@Override
									public void renderText(TextRenderInfo textRenderInfo) {
										String text = textRenderInfo.getText();
										com.itextpdf.awt.geom.Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
										if(yy == -1f) {
											yy = boundingRectange.y;
										}
										if(yy != boundingRectange.y) {
											yy = boundingRectange.y;
											pdfsb.setLength(0);
										}
										pdfsb.append(text);
										if (pdfsb.length()>0 && pdfsb.toString().contains(key_word)) {
											float[] resu = new float[3];
											resu[0] = BigDecimal.valueOf(boundingRectange.x).add(BigDecimal.valueOf(20)).floatValue();
											resu[1] = BigDecimal.valueOf(boundingRectange.y) .subtract(BigDecimal.valueOf(12)).floatValue();
											resu[2] = finalI;
											arrays.add(resu);
											pdfsb.setLength(0);
										} else if (pdfsb.length()>0 && pdfsb.toString().contains(DATE_KEY_WORD)) {
											float[] resu = new float[3];
											resu[0] = BigDecimal.valueOf(boundingRectange.x).add(BigDecimal.valueOf(20)).floatValue();
											resu[1] = BigDecimal.valueOf(boundingRectange.y) .subtract(BigDecimal.valueOf(5)).floatValue();
											resu[2] = finalI;
											date_arrays.add(resu);
											pdfsb.setLength(0);
										}
									}
									@Override
									public void renderImage(ImageRenderInfo arg0) {}
									@Override
									public void endTextBlock() {}
									@Override
									public void beginTextBlock() {}
								});
							}
						}
					}
				}
				//没有配关键字,或者关键字不存在，则使用配置的坐标系
				if (ObjectUtil.isEmpty(arrays)) {
					Rectangle rect = pdfReader.getPageSize(pageNum);
					BigDecimal x = BigDecimal.valueOf(164);
					BigDecimal y = BigDecimal.valueOf(107);
					if (!ObjectUtil.isEmpty(signCfg.get("bar_left"))) {
						x = new BigDecimal(signCfg.get("bar_left"));
					}
					if (!ObjectUtil.isEmpty(signCfg.get("bar_top"))) {
						y = BigDecimal.valueOf(rect.getHeight()) .subtract(new BigDecimal(signCfg.get("bar_top")))  .subtract(height) ;
					}
					float[] resu = new float[3];
					resu[0] = x.floatValue();
					resu[1] = y.floatValue();
					resu[2] = new Float(pageNum);
					arrays.add(resu);
				}
				//当且仅当页面上有签字的地方，才会生成相应的签字时间
				if (!ObjectUtil.isEmpty(date_arrays) && !ObjectUtil.isEmpty(arrays)) {
					//构造签字时间字符串图片
					BaseService bs = (BaseService) ServiceManager.getService("baseService");
					String sign_date = DateUtil.timestamp2Str(bs.getSysTimestamp(), "yyyy-MM-dd HH:mm:ss");
					if (!ObjectUtil.isEmpty(sign_date)) {
						int date_width = 120;
						int date_height = 15;
						BufferedImage localBufferedImage = new BufferedImage(date_width,date_height, BufferedImage.TYPE_INT_RGB);
						Graphics2D localGraphics2D = localBufferedImage.createGraphics();
						//设置背景为透明
//						localBufferedImage = localGraphics2D.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
//						localGraphics2D.dispose();
//						localGraphics2D = localBufferedImage.createGraphics();
						localGraphics2D.setFont(new Font("宋体", Font.PLAIN, 12));
						localGraphics2D.setColor(Color.white);
						localGraphics2D.fillRect(0, 0, date_width, date_height);
						localGraphics2D.setColor(Color.black);
						localGraphics2D.setStroke(new BasicStroke(1.5F));
						localGraphics2D.drawString(sign_date.trim(), 2, 10);
						localGraphics2D.dispose();
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						ImageOutputStream imOut;
						try {
							imOut = ImageIO.createImageOutputStream(baos);
							ImageIO.write(localBufferedImage, "jpg", imOut);
							date_is = new ByteArrayInputStream(baos.toByteArray());
						} catch (IOException e) {
							LogUtil.error(e);
						}
					}
				}
				Image img = null;
				PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
				//默认只签最后一处所在页
				PdfContentByte over = pdfStamper.getOverContent((int)arrays.get(arrays.size()-1)[2]);
				try {
					//签字时间
					img = getImgByInputstream(date_is);
					if (!ObjectUtil.isEmpty(img) ) {
						img.scaleAbsolute(105, 15);// 控制最终图片大小(缩放效果)
						if (SibpmConstant.YES.equals(signCfg.get("is_every"))) {
							for (int j=0; j<date_arrays.size(); j++) {
								img.setAbsolutePosition(date_arrays.get(j)[0], date_arrays.get(j)[1]);// 控制图片位置
								over = pdfStamper.getOverContent((int)date_arrays.get(j)[2]);
								over.addImage(img);
							}
						} else {
							img.setAbsolutePosition(date_arrays.get(date_arrays.size()-1)[0], date_arrays.get(date_arrays.size()-1)[1]);// 控制图片位置
							over.addImage(img);
						}
					}
					img = getImgByInputstream(is);
					if (!ObjectUtil.isEmpty(img) ) {
						img.setAlignment(1);
						img.scaleAbsolute(width.floatValue(), height.floatValue());// 控制图片大小
						//每页都签字
						if (SibpmConstant.YES.equals(signCfg.get("is_every"))) {
							for (int j=0; j<arrays.size(); j++) {
								img.setAbsolutePosition(arrays.get(j)[0], arrays.get(j)[1]);// 控制图片位置
								over = pdfStamper.getOverContent((int)arrays.get(j)[2]);
								over.addImage(img);
							}
						} else {
							img.setAbsolutePosition(arrays.get(arrays.size()-1)[0], arrays.get(arrays.size()-1)[1]);// 控制图片位置
							over.addImage(img);
						}
					}
				} catch (Exception e){
					LogUtil.error(e);
				}
				pdfStamper.close();
			}
		} catch (Exception e) {
			LogUtil.error(e);
		}
	}*/

	/**
	 * 给pdf文件生成打印信息,包括电子签章
	 *
	 * @param outputStream pdf流
	 * @param dto 打印信息
	 */
	/*public static void pdfAddPrintInfo(OutputStream outputStream, ParamDTO dto) {
		if (ObjectUtil.isEmpty(outputStream)) {
			return;
		}
		String userName = "";
		String yab003 = "";
		try {
			userName = dto.getUserInfo().getName();
			yab003 = dto.getUser().getNowPosition().getOrgnamepath();
			if (yab003.contains("/")) {
				yab003 = yab003.substring(yab003.lastIndexOf("/")+1);
			}
			//yab003 = CodeTableUtil.getDesc("YAB003", dto.getUserInfo().getYab003());
		} catch (Exception e) {

		}
		if (ObjectUtil.isEmpty(userName)) {
			//网厅没有dto,使用他们传过来的print_person和print_org(约定字段)
			userName = dto.getAsString("print_person");
			yab003 = dto.getAsString("print_org");
		}
		List<String> keyWords = new ArrayList<String>();
		Map specialMap = (Map)getSpecialSignMap().get(dto.getAsString("report_code"));
		keyWords.add("打印人");
		keyWords.add("打印机构");
		keyWords.add("打印时间");
		keyWords.add("审核人");
		BaseService bs = (BaseService) ServiceManager.getService("baseService");
		String signDate = DateUtil.timestamp2Str(bs.getSysTimestamp(), "yyyy-MM-dd HH:mm:ss");
		try {
			PdfReader pdfReader;
			pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
			List<List<float[]>> arrayLists = findKeywordLocations(keyWords, pdfReader);
			//一个坐标也没找到，遛了溜了
			if (ObjectUtil.isEmpty(arrayLists)) {
				return;
			}
			//20181112 电子印章添加太严格，经框架hucf确认允许删除此判断
			// if (!ObjectUtil.isEmpty(arrayLists) && (!ObjectUtil.isEmpty(arrayLists.get(0))&&!ObjectUtil.isEmpty(arrayLists.get(1)) || !ObjectUtil.isEmpty(arrayLists.get(2)))) {
				PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
				//每页都加
				BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
				int lineNum = 10;
				if (!ObjectUtil.isEmpty(arrayLists.get(0))) {
					for (int i=0; i<arrayLists.get(0).size(); i++) {
						PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(0).get(i)[2]);
						overContent.beginText();
						overContent.setFontAndSize(font, 10);
						overContent.setTextMatrix(200, 200);
						int row = userName.length()/lineNum;
						row++;
						int lastIndex = userName.length();
						for (int j=0; j<row; j++) {
							lastIndex = (j+1)*lineNum>userName.length()?userName.length():(j+1)*lineNum;
							overContent.showTextAligned(Element.ALIGN_LEFT, userName.substring(j*lineNum, lastIndex), arrayLists.get(0).get(i)[0], arrayLists.get(0).get(i)[1]-j*15, 0);
						}
						//overContent.showTextAligned(Element.ALIGN_LEFT, userName, arrayLists.get(0).get(i)[0], arrayLists.get(0).get(i)[1], 0);
						overContent.endText();
					}
				}
			if(!ObjectUtil.isEmpty(arrayLists.get(1))){
				for (int i=0; i<arrayLists.get(1).size(); i++) {
					PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(1).get(i)[2]);
					overContent.beginText();
					overContent.setFontAndSize(font, 10);
					overContent.setTextMatrix(200, 200);
					int row = yab003.length()/lineNum;
					row++;
					int lastIndex = yab003.length();
					for (int j=0; j<row; j++) {
						lastIndex = (j+1)*lineNum>yab003.length()?yab003.length():(j+1)*lineNum;
						overContent.showTextAligned(Element.ALIGN_LEFT, yab003.substring(j*lineNum, lastIndex), arrayLists.get(1).get(i)[0] - 10, arrayLists.get(1).get(i)[1]-j*15, 0);
					}
					overContent.endText();
					if (SibpmConstant.YES.equals(dto.getAsString("isSeal"))) {
                            //新疆需求：给打印机构加签章图片
                            try {
                                //String imgPath = "/resource/lodop/sign.png";
                                String imgPath;//判断不同地州用不同电子签章:20180329wangxh加
                                String yab003_zh = "";
                                if (ValidateUtil.isEmpty(dto.getUserInfo())) {
                                    yab003_zh = dto.getAsString("yab139");
                                } else {
                                    yab003_zh = dto.getUserInfo().getYab003();
                                }
                                if (ValidateUtil.isEmpty(yab003_zh)) {
                                    yab003_zh = "650100";//如果没有获取到经办机构就打乌鲁木齐市的，防止为空报错
                                }
                                String yab139 = yab003_zh;
                                yab003_zh = yab003_zh.substring(0, 4);
                                imgPath = "/resource/lodop/sign" + yab003_zh + ".png";


                                BigDecimal sealWidth = BigDecimal.valueOf(150f);
                                BigDecimal sealHeight = BigDecimal.valueOf(95f);
                                BigDecimal absoluteX = BigDecimal.valueOf(arrayLists.get(1).get(i)[0]).subtract(BigDecimal.valueOf(90));
                                BigDecimal absoluteY = BigDecimal.valueOf(arrayLists.get(1).get(i)[1]).subtract(sealHeight.divide(BigDecimal.valueOf(2)));
                                if ("6501".equals(yab003_zh.substring(0, 4)) || "659904".equals(yab139)) {
                                    //仅仅计算乌市，有特殊电子签章需求
                                    if (!ValidateUtil.isEmpty(specialMap)) {
                                        imgPath = (String) specialMap.get("imgPath");
                                        sealWidth = (BigDecimal) specialMap.get("sealWidth");
                                        sealHeight = (BigDecimal) specialMap.get("sealHeight");
                                        absoluteX = (BigDecimal) specialMap.get("absoluteX");
                                        absoluteY = (BigDecimal) specialMap.get("absoluteY");
                                    }
                                }
                                InputStream pageHeaderInputstream = PDFUtil.class.getClassLoader().getResourceAsStream(imgPath);
                                Image pageHeaderImg = getImgByInputstream(pageHeaderInputstream);
                                pageHeaderImg.setAlignment(Element.ALIGN_LEFT);
                                pageHeaderImg.scaleAbsolute(sealWidth.floatValue(), sealHeight.floatValue());// 控制签章大小
                                pageHeaderImg.setAbsolutePosition(absoluteX.floatValue(), absoluteY.floatValue());// 控制图片位置
                                overContent.addImage(pageHeaderImg);
                      } catch (Exception e) {
                           LogUtil.error(e);
                      }
                    }
				}
			}else if(!ObjectUtil.isEmpty(arrayLists.get(3))&&!ValidateUtil.isEmpty(specialMap)){
					for (int i=0; i<arrayLists.get(3).size(); i++) {
						PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(3).get(i)[2]);
						if (SibpmConstant.YES.equals(dto.getAsString("isSeal"))) {
							//新疆需求：给打印机构加签章图片
							try {
								//String imgPath = "/resource/lodop/sign.png";
								String imgPath;//判断不同地州用不同电子签章:20180329wangxh加
								String yab003_zh = "";
								if (ValidateUtil.isEmpty(dto.getUserInfo())) {
									yab003_zh = dto.getAsString("yab139");
								} else {
									yab003_zh = dto.getUserInfo().getYab003();
								}
								if (ValidateUtil.isEmpty(yab003_zh)) {
									yab003_zh = "650100";//如果没有获取到经办机构就打乌鲁木齐市的，防止为空报错
								}
								String yab139 = yab003_zh;
								yab003_zh = yab003_zh.substring(0, 4);
								imgPath = "/resource/lodop/sign" + yab003_zh + ".png";


								BigDecimal sealWidth = BigDecimal.valueOf(150f);
								BigDecimal sealHeight = BigDecimal.valueOf(95f);
								BigDecimal absoluteX = BigDecimal.valueOf(arrayLists.get(3).get(i)[0]).subtract(BigDecimal.valueOf(90));
								BigDecimal absoluteY = BigDecimal.valueOf(arrayLists.get(3).get(i)[1]).subtract(sealHeight.divide(BigDecimal.valueOf(2)));
								if ("6501".equals(yab003_zh.substring(0, 4)) || "659904".equals(yab139)) {
									//仅仅计算乌市，有特殊电子签章需求
									if (!ValidateUtil.isEmpty(specialMap)) {
										imgPath = (String) specialMap.get("imgPath");
										sealWidth = (BigDecimal) specialMap.get("sealWidth");
										sealHeight = (BigDecimal) specialMap.get("sealHeight");
										absoluteX = (BigDecimal) specialMap.get("absoluteX");
										absoluteY = (BigDecimal) specialMap.get("absoluteY");
									}
								}
								InputStream pageHeaderInputstream = PDFUtil.class.getClassLoader().getResourceAsStream(imgPath);
								Image pageHeaderImg = getImgByInputstream(pageHeaderInputstream);
								pageHeaderImg.setAlignment(Element.ALIGN_LEFT);
								pageHeaderImg.scaleAbsolute(sealWidth.floatValue(), sealHeight.floatValue());// 控制签章大小
								pageHeaderImg.setAbsolutePosition(absoluteX.floatValue(), absoluteY.floatValue());// 控制图片位置
								overContent.addImage(pageHeaderImg);
							} catch (Exception e) {
								LogUtil.error(e);
							}
						}
					}
				}

				if (!ObjectUtil.isEmpty(arrayLists.get(2))) {
					for (int i=0; i<arrayLists.get(2).size(); i++) {
						PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(2).get(i)[2]);
						overContent.beginText();
						overContent.setFontAndSize(font, 10);
						overContent.setTextMatrix(200, 200);
						overContent.showTextAligned(Element.ALIGN_LEFT, signDate, arrayLists.get(2).get(i)[0] - 10, arrayLists.get(2).get(i)[1], 0);
						overContent.endText();
					}
				}
				pdfStamper.close();
			//}
		} catch (Exception e) {
			LogUtil.error(e);
		}
	}*/

	/**
	 * 给pdf文件生成打印信息,包括电子签章659900区本级
	 *返回base64字符串
	 */
	/*public static String pdfAddPrintInfoSignature(OutputStream outputStream, ParamDTO dto) {
	    String fileBase64 = "";
		if (ObjectUtil.isEmpty(outputStream)) {
			return null;
		}
		String userName = "";
		String yab003 = "";
		try {
			userName = dto.getUserInfo().getName();
			yab003 = dto.getUser().getNowPosition().getOrgnamepath();
			if (yab003.contains("/")) {
				yab003 = yab003.substring(yab003.lastIndexOf("/")+1);
			}
			//yab003 = CodeTableUtil.getDesc("YAB003", dto.getUserInfo().getYab003());
		} catch (Exception e) {

		}
		if (ObjectUtil.isEmpty(userName)) {
			//网厅没有dto,使用他们传过来的print_person和print_org(约定字段)
			userName = dto.getAsString("print_person");
			yab003 = dto.getAsString("print_org");
		}
		List<String> keyWords = new ArrayList<String>();
//		Map specialMap = (Map)getSpecialSignMap().get(dto.getAsString("report_code"));
		keyWords.add("打印人");
		keyWords.add("打印机构");
		keyWords.add("打印时间");
		keyWords.add("审核人");
		BaseService bs = (BaseService) ServiceManager.getService("baseService");
		String signDate = DateUtil.timestamp2Str(bs.getSysTimestamp(), "yyyy-MM-dd HH:mm:ss");
		try {
			PdfReader pdfReader;
			pdfReader = new PdfReader(((ByteArrayOutputStream)outputStream).toByteArray());
			List<List<float[]>> arrayLists = findKeywordLocations(keyWords, pdfReader);
			//一个坐标也没找到，遛了溜了
			if (ObjectUtil.isEmpty(arrayLists)) {
				return fileBase64;
			}
			//20181112 电子印章添加太严格，经框架hucf确认允许删除此判断
			// if (!ObjectUtil.isEmpty(arrayLists) && (!ObjectUtil.isEmpty(arrayLists.get(0))&&!ObjectUtil.isEmpty(arrayLists.get(1)) || !ObjectUtil.isEmpty(arrayLists.get(2)))) {
			PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
			//每页都加
			BaseFont font = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			int lineNum = 10;
			if (!ObjectUtil.isEmpty(arrayLists.get(0))) {
				for (int i=0; i<arrayLists.get(0).size(); i++) {
					PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(0).get(i)[2]);
					overContent.beginText();
					overContent.setFontAndSize(font, 10);
					overContent.setTextMatrix(200, 200);
					int row = userName.length()/lineNum;
					row++;
					int lastIndex = userName.length();
					for (int j=0; j<row; j++) {
						lastIndex = (j+1)*lineNum>userName.length()?userName.length():(j+1)*lineNum;
						overContent.showTextAligned(Element.ALIGN_LEFT,userName.substring(j*lineNum, lastIndex),arrayLists.get(0).get(i)[0],arrayLists.get(0).get(i)[1]-j*15,0);
					}
					//overContent.showTextAligned(Element.ALIGN_LEFT, userName, arrayLists.get(0).get(i)[0], arrayLists.get(0).get(i)[1], 0);
					overContent.endText();
				}
			}
			if(!ObjectUtil.isEmpty(arrayLists.get(1))){
				for (int i=0; i<arrayLists.get(1).size(); i++) {
					PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(1).get(i)[2]);
					overContent.beginText();
					overContent.setFontAndSize(font, 10);
					overContent.setTextMatrix(200, 200);
					int row = yab003.length()/lineNum;
					row++;
					int lastIndex = yab003.length();
					for (int j=0; j<row; j++) {
						lastIndex = (j+1)*lineNum>yab003.length()?yab003.length():(j+1)*lineNum;
						overContent.showTextAligned(Element.ALIGN_LEFT, yab003.substring(j*lineNum, lastIndex), arrayLists.get(1).get(i)[0] - 10, arrayLists.get(1).get(i)[1]-j*15, 0);
					}
					overContent.endText();
				}
			}
			if (!ObjectUtil.isEmpty(arrayLists.get(2))) {
				for (int i=0; i<arrayLists.get(2).size(); i++) {
					PdfContentByte overContent = pdfStamper.getOverContent((int)arrayLists.get(2).get(i)[2]);
					overContent.beginText();
					overContent.setFontAndSize(font, 10);
					overContent.setTextMatrix(200, 200);
					overContent.showTextAligned(Element.ALIGN_LEFT, signDate, arrayLists.get(2).get(i)[0] - 10, arrayLists.get(2).get(i)[1], 0);
					overContent.endText();
				}
			}
			if ("1".equals(dto.getAsString("signType"))) {
				Map param = new HashMap();
				param.put("orderId", dto.get("orderId")); //业务码值
				param.put("title", dto.get("title")); //文档标题
				param.put("file", getBase64FromInputStream(outPut2InPutStream(outputStream))); //文件
				param.put("sealCode", dto.get("sealCode")); //印章编码
				param.put("positionType", dto.get("positionType")); //文字  绝对位置印章
				param.put("text",dto.get("text"));
				param.put("x",dto.get("x")); //x
				param.put("y",dto.get("y")); //y
				param.put("page",dto.get("page")); //指定打印页   0表示所有页,其余表示指定页，多页用逗号隔开
                fileBase64 = getElectronicSignature(param);
				pdfStamper.close();
			}
		} catch (Exception e) {
			LogUtil.error(e);
		} finally {
			return fileBase64;
		}
	}*/

	public static Map getSpecialSignMap() {
		return specialConfigMap;
	}

	/**
	 * 将inputstream转换成image
	 * @param is
	 * @return
	 */
	/*private static Image getImgByInputstream(InputStream is) {
		if (ObjectUtil.isEmpty(is)) {
			return null;
		}
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		Image img = null;
		try {
			readInputStream(is, output);
			try {
				img = Image.getInstance(output.toByteArray());
			} catch (BadElementException e) {
				LogUtil.error(e);
			}
		} catch (IOException e) {
			LogUtil.error(e);
		}
		return img;
	}*/

	/**
	 * 将inputstream读入到outputstream中
	 * @param inputStream
	 * @param outputStream
	 * @return
	 * @throws IOException
	 */
	public static void readInputStream(InputStream inputStream, OutputStream outputStream) throws IOException{

		byte[] buffer = new byte[2048];
		int n = 0;
		while (-1 != (n = inputStream.read(buffer))) {
			outputStream.write(buffer, 0, n);
		}
		inputStream.close();
	}

	/**
	 * 转换yuf003至yue013
	 */
	/*public static String parseYue013(String yuf003) {
		if (ObjectUtil.isEmpty(yuf003) || yuf003.length() < 11) {
			return null;
		}
		return yuf003.substring(yuf003.length() - 10, yuf003.length() - 5);
	}*/

	/**
	 * 把Map<String,Object>转成Map<String,String>
	 *
	 * @param reportData
	 * @return
	 */
	/*private static Map<String, String> Object2String(Map<String, Object> reportData) {
		if (ObjectUtil.isEmpty(reportData)) {
			return null;
		}
		Map<String, String> returnData = new HashMap<String, String>();
		Iterator<Map.Entry<String, Object>> it = reportData.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, Object> entry = it.next();
			returnData.put(entry.getKey(), String.valueOf(entry.getValue()));
		}
		return returnData;
	}*/

	/**
	 * 根据关键字返回对应的坐标
	 * @param keyWords
	 * @param pdfReader
	 * @return
	 */
	/*private static List<List<float[]>> findKeywordLocations(final List<String> keyWords, PdfReader pdfReader) {
		if (ObjectUtil.isEmpty(keyWords)) {
			return null;
		}
		int pageNum = pdfReader.getNumberOfPages();
		final List<List<float[]>> arrayLists = new ArrayList<List<float[]>>(keyWords.size());
		for (int k=0; k<keyWords.size(); k++) {
			List<float[]> positions = new ArrayList<float[]>();
			arrayLists.add(positions);
		}
		PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
		try {
			for (int i = 1; i <= pageNum; i++) {
				final int finalI = i;
				pdfReaderContentParser.processContent(i, new RenderListener() {
					private StringBuilder pdfsb = new StringBuilder();
					private float yy = -1f;
					@Override
					public void renderText(TextRenderInfo textRenderInfo) {
						String text = textRenderInfo.getText();
						com.itextpdf.awt.geom.Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();
						if(yy == -1f) {
							yy = boundingRectange.y;
						}
						if(yy != boundingRectange.y) {
							yy = boundingRectange.y;
							pdfsb.setLength(0);
						}
						pdfsb.append(text);
						if (pdfsb.length()>0) {
							for (int j=0; j<keyWords.size(); j++) {
								if (pdfsb.length()>0 && pdfsb.toString().contains(keyWords.get(j))) {
									float[] resu = new float[3];
									//resu[0] = boundingRectange.x + boundingRectange.width * (keyWords.get(j).length()-1);
									resu[0] = BigDecimal.valueOf(boundingRectange.x).add( BigDecimal.valueOf(boundingRectange.width).multiply( BigDecimal.valueOf(keyWords.get(j).length()-1)) ).floatValue() ;
									resu[1] = boundingRectange.y;
									resu[2] = finalI;
									arrayLists.get(j).add(resu);
									pdfsb.setLength(0);
									break;
								}
							}
						}
					}
					@Override
					public void renderImage(ImageRenderInfo arg0) {}
					@Override
					public void endTextBlock() {}
					@Override
					public void beginTextBlock() {}
				});
			}
		} catch (Exception e) {
			LogUtil.error(e);
		}
		return arrayLists;
	}*/

	/**
	 * 将pdf流转成Base64字符串，方便传输
	 * 生成文件的MD5校验码
	 *
	 * @param inputStream
	 */
	/*public static Map<String, String> convertPdfToBase64(InputStream inputStream) {
		Map<String, String> result = new HashMap<String, String>();
		if (ObjectUtil.isEmpty(inputStream)) {
			result.put("success", SibpmConstant.NO);
			result.put("err_msg", "生成单据失败，错误原因：未生成临时文件流");
			return result;
		}
		try {
			int n = 0;
			byte[] sPdfBytes = new byte[2048];
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			while ((n = inputStream.read(sPdfBytes)) != -1) {
				outputStream.write(sPdfBytes, 0, n);
			}
			String PdfBase64 = Base64.encodeBase64String(outputStream.toByteArray());
			String PdfMd5 = MD5Util.MD5(sPdfBytes);
			result.clear();
			result.put("success", SibpmConstant.YES);
			result.put("PdfBase64", PdfBase64);
			result.put("PdfMd5", PdfMd5);
		} catch (Exception e) {
			LogUtil.error(e);
		}
		return result;
	}*/

	/**
	 * 将图片流转成Base64字符串，方便传输
	 * 生成文件的MD5校验码
	 *
	 * @param
	 * @return
	 */
	/*public static Map<String, String> convertImagesToBase64(List<InputStream> inputStreamList) {
		Map<String, String> result = new HashMap<String, String>();
		if (ObjectUtil.isEmpty(inputStreamList)) {
			result.put("success", SibpmConstant.NO);
			result.put("err_msg", "生成单据失败，错误原因：生成图片流为空");
			return result;
		}
		List<String> imageBase64List = new ArrayList<>();
		List<String> imageMd5List = new ArrayList<>();
		try {
			for (InputStream inputStream:inputStreamList) {
				int n = 0;
				byte[] simageBytes = new byte[2048];
				ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
				while ((n = inputStream.read(simageBytes)) != -1) {
					outputStream.write(simageBytes, 0, n);
				}
				String imageBase64 = Base64.encodeBase64String(outputStream.toByteArray());
				String imageMd5 = MD5Util.MD5(simageBytes);
				imageBase64List.add(imageBase64);
				imageMd5List.add(imageMd5);
			}
			result.clear();
			result.put("success", SibpmConstant.YES);
			result.put("imageBase64", JsonUtil.toJson(imageBase64List));
			result.put("imageMd5", JsonUtil.toJson(imageMd5List));
		} catch (Exception e) {
			LogUtil.error(e);
		}
		return result;
	}*/

	// outputStream转inputStream
	public static ByteArrayInputStream outPut2InPutStream(OutputStream out) throws IOException {
		ByteArrayOutputStream baos;
		baos = (ByteArrayOutputStream) out;
		final ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
		return swapStream;
	}

    /**
     * 区本级电子签章
     */
    /*public static String getElectronicSignature(Map map) throws Exception {

        String xmlInput = map2Xml(map);
        String wsdlUrl = SysConfig.getSysConfig("wsdlurl");
        Client client = WebServiceUtil.getClient(wsdlUrl);
        client.getOutInterceptors().add(new AddSoapHeader("http://yinhai.com","publicBusiness",xmlInput, xmlInput,"getSealByPDF"));

        Object[] obj = client.invoke("callBusiness", xmlInput); //发起调用
        client.getOutInterceptors().clear();

        Object temp = obj[0]; //获取返回结果(XML格式)
        Map resultMap = xml2Map(String.valueOf(temp));
		if(!ValidateUtil.isEmpty(resultMap.get("data"))){
			return resultMap.get("data").toString();
		}
		return null;
    }*/
	/**
	 * xml2Map 方法
	 * <p>方法说明:将传入的xml转换为Map对象</p>
	 * @param xml 传入xml字符串
	 * @return Map
	 * @author Hyman
	 * @date 2014-9-12
	 */
	/*private static Map xml2Map(String xml) {
		Map<String, String> map = new HashMap<String, String>();
		SAXBuilder sb = new SAXBuilder();
		Reader reader = new StringReader(xml);
		try {
			org.jdom.Document document = sb.build(reader);
			org.jdom.Element rootElement = document.getRootElement();
			List list = (List)rootElement.getChildren();
			if (rootElement.getChildren().size() != 0) {
				org.jdom.Element el = null;
				for (Iterator iter = list.iterator(); iter.hasNext();) {
					el = (org.jdom.Element) iter.next();
					map.put(el.getName(), el.getText());
				}
			}
		} catch (JDOMException e) {
			LogUtil.error(e);
		} catch (IOException e) {
			LogUtil.error(e);
		}
		return map;
	}*/
	/**
	 * map2Xml 方法
	 * <p>方法说明:将传入的Map转换为xml格式，如直接将dto传入</p>
	 * @param param 参数Map
	 * @return String 返回xml字符串
	 * @author Hyman
	 * @date 2014-9-12
	 */
	private static String map2Xml(Map param) {
		if (param == null || param.size() == 0) {
			return "<input></input>";
		}
		StringBuffer result = new StringBuffer();
		result.append("<input>");
		Set<String> set = param.keySet();
		Iterator it = set.iterator();
		Object object = null;
		while (it.hasNext()) {
			object = it.next();
			result.append("<").append(String.valueOf(object)).append(">");
			if((param.get(object)) instanceof Clob) {// ]]
				result.append(clob2String((Clob)param.get(object)));
			} else {
				result.append(String.valueOf(param.get(object)));
			}
			result.append("</").append(String.valueOf(object)).append(">");
		}
		result.append("</input>");
		return result.toString();
	}
	/**
	 * Clob类型转换成String类型
	 * @param clob
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	private static String clob2String(Clob clob) {

		String reString = "";
		try {
			// 得到流
			Reader is = clob.getCharacterStream();
			BufferedReader br = new BufferedReader(is);
			String s = br.readLine();
			StringBuffer sb = new StringBuffer();
			while (s != null) {// 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
				sb.append(s);
				s = br.readLine();
			}
			reString = sb.toString();
		} catch (SQLException e) {
			LogUtil.error(e);
		} catch (IOException e) {
			LogUtil.error(e);
		}

		return reString;
	}
	/**
	 * base64转inputStream
	 * @param base64string
	 * @return
	 */
	public static InputStream BaseToInputStream(String base64string){
		ByteArrayInputStream stream = null;
		try {
			BASE64Decoder decoder = new BASE64Decoder();
			byte[] bytes1 = decoder.decodeBuffer(base64string);
			stream = new ByteArrayInputStream(bytes1);
		} catch (Exception e) {
			LogUtil.error(e);
		}
		return stream;
	}

	/**
	 * InputStream转Base64
	 * @param in
	 * @return
	 */
	public static String getBase64FromInputStream(InputStream in) {
		// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		byte[] data = null;
		// 读取图片字节数组
		try {
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[4096];
			int rc = 0;
			while ((rc = in.read(buff, 0, 100)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			data = swapStream.toByteArray();
		} catch (IOException e) {
			LogUtil.error(e);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LogUtil.error(e);
				}
			}
		}
		return new String(Base64.encodeBase64(data));
	}

	/*** @Description:Base64转换成pdf
	 * @param pdfBase64Str ⼆进制字符串r
	 * @param filepath 保存路径
	 */
	public static void BasetoPdffile(String pdfBase64Str, String filepath) {
		byte[] bytes = Base64.decodeBase64(pdfBase64Str);
		File file = new File(filepath);
		File path = file.getParentFile();
		if (!path.exists()) {
			path.mkdirs();
		}

		try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
			BufferedInputStream bis = new BufferedInputStream(byteArrayInputStream);
			FileOutputStream fos = new FileOutputStream(file);
			BufferedOutputStream bos = new BufferedOutputStream(fos)) {
			byte[] buffer = new byte[1024];
			int length = bis.read(buffer);
			while (length != -1) {
				bos.write(buffer, 0, length);
				length = bis.read(buffer);
			}
			bos.flush();
		} catch (Exception e) {
			LogUtil.error(e);
		} finally {

		}
	}

}
